import {
  createRouter,
  createWebHistory,
  createWebHashHistory,
  RouteRecordRaw,
} from 'vue-router';

import Home from '../views/Home.vue';

import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

import store from '@store/index';

// 基础路由
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    component: Home,
    redirect: '/main',
    children: [
      {
        path: '/main',
        component: () => import('@views/Main/Main.vue'),
      },
      {
        path: '/home',
        component: () => import('@views/Common/Home/HomePage.vue'),
        children: [
          {
            path: '/rank',
            component: () => import('@views/Rank/Rank.vue'),
          },
          {
            path: '/forum',
            component: () => import('@views/Forum/Forum.vue'),
          },
          {
            path: '/personal',
            component: () => import('@views/Personal/Personal.vue'),
          },
          {
            path: '/portal',
            component: () => import('@views/Portal/Portal.vue'),
          },
          {
            path: '/expert',
            component: () => import('@views/Expert/Expert.vue'),
          },
          {
            path: '/result',
            component: () =>
              import('@views/Search/SearchResult/SearchResult.vue'),
          },
          {
            path: '/detail',
            component: () =>
              import('@views/Search/AchieveDetail/AchieveDetail.vue'),
          },
          {
            path: '/message',
            component: () => import('@views/Message/Message.vue'),
          },
        ],
      },
      {
        path: '/login',
        component: () => import('@views/Common/Login/Login.vue'),
      },
      {
        path: '/manage',
        component: () => import('@views/Manage/Manage.vue'),
      },
    ],
  },
  {
    path: '/:catchAll(.*)',
    name: '404',
    component: () => import('@views/Common/Error/404.vue'),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      // 通过前进后台时才触发
      return savedPosition;
    } else {
      return { top: 0, behavior: 'smooth' };
    }
  },
});

// 访问控制
router.beforeEach((to, from, next) => {
  // if (to.path === '/login') {
  //   if (store.state.auth) {
  //     next('/home');
  //   } else {
  //     NProgress.start();
  //     next();
  //   }
  // } else if (to.path.indexOf('/q/') >= 0) {
  //   if (store.state.auth) {
  //     NProgress.start();
  //     next();
  //   } else {
  //     next('/login');
  //   }
  // } else {
  //   NProgress.start();
  next();
  // }
});

router.afterEach(() => {
  NProgress.done();
});

export default router;
